﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InWare.InNutri.Model;
using System.Windows.Input;
using System.ComponentModel;
using InWare.InNutri.Applications.Util;
using System.Windows;
using System.Data;
using System.Windows.Media.Imaging;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;

namespace InWare.InNutri.Applications.ViewModels
{
    public class PacienteViewModel : 
        EntityViewModelBase<Paciente>
    {
        private InNutriContext _context;
        private bool _formContext;

        #region Constructor
        
        public PacienteViewModel(Paciente paciente)
            : base(paciente)
        {
            this.OkCommand = new DelegateCommand((o) => this.SavePaciente(), (o) => this.CanSavePaciente());
            this.CancelarCommand = new DelegateCommand((o) => this.Cancelar());
            this.AddEnderecoCommand = new DelegateCommand((o) => this.AddEndereco());
            this.RemoveEnderecoCommand = new DelegateCommand((o) => this.RemoveEndereco(), (o) => this.CanRemoveEndereco());
            this.OpenFotoFileCommand = new DelegateCommand((o) => this.OpenFotoFile());

            this._context = new InNutriContext();
        }


        #endregion

        #region Public properties

        #region Geral
        public string Nome
        {
            get { return base.Entity.Nome; }
            set { base.Entity.Nome = value; }
        }

        public DateTime DataDeNascimento
        {
            get { return base.Entity.DataDeNascimento; }
            set
            {
                base.Entity.DataDeNascimento = value;
                base.OnPropertyChanged("Idade");
            }
        }

        public string Idade
        {
            get
            {
                TimeSpan idade = DateTime.Now - DataDeNascimento;

                int anos = Convert.ToInt32(idade.TotalDays / 365);
                int meses = Convert.ToInt32((idade - TimeSpan.FromDays(anos * 365)).TotalDays / 30);

                return string.Format("{0} anos, {1} meses e {2} dias", anos, meses, 0);
            }
        }

        public bool SexoMasculino
        {
            get { return base.Entity.Sexo != null? base.Entity.Sexo.IdSexo == 2 : false; }
            set
            {
                if (value)
                {
                    base.Entity.Sexo = _context.SexoSet.First(s => s.IdSexo == 2);
                }
                else
                {
                    base.Entity.Sexo = _context.SexoSet.First(s => s.IdSexo == 1);
                }

                base.OnPropertyChanged("SexoMasculino");

                if (base.Entity.EntityState == EntityState.Unchanged)
                {
                    _context.ObjectStateManager.ChangeObjectState(base.Entity, EntityState.Modified);
                }
            }
        }

        public bool SexoFeminino
        {
            get { return base.Entity.Sexo != null? base.Entity.Sexo.IdSexo == 1 : false; }
            set
            {
                if (value)
                {
                    base.Entity.Sexo = _context.SexoSet.First(s => s.IdSexo == 1);
                }
                else
                {
                    base.Entity.Sexo = _context.SexoSet.First(s => s.IdSexo == 2);
                }

                base.OnPropertyChanged("SexoFeminino");

                if (base.Entity.EntityState == EntityState.Unchanged)
                {
                    _context.ObjectStateManager.ChangeObjectState(base.Entity, EntityState.Modified);
                }
            }
        }

        public EstadoCivil EstadoCivilPaciente
        {
            get { return base.Entity.EstadoCivil; }
            set
            {
                base.Entity.EstadoCivil = value;
                base.OnPropertyChanged("EstadoCivilPaciente");

                if (base.Entity.EntityState == EntityState.Unchanged)
                {
                    _context.ObjectStateManager.ChangeObjectState(base.Entity, EntityState.Modified);
                }
            }
        }

        public GrupoEspecifico GrupoEspecificoPaciente
        {
            get { return base.Entity.GrupoEspecifico; }
            set
            {
                base.Entity.GrupoEspecifico = value;
                base.OnPropertyChanged("GrupoEspecificoPaciente");
                
                if (base.Entity.EntityState == EntityState.Unchanged)
                {
                    _context.ObjectStateManager.ChangeObjectState(base.Entity, EntityState.Modified);
                }
            }
        }

        public string Naturalidade
        {
            get { return base.Entity.Naturalidade; }
            set { base.Entity.Naturalidade = value; }
        }

        public Etnia EtniaPaciente
        {
            get { return base.Entity.Etnia; }
            set
            {
                base.Entity.Etnia = value;
                base.OnPropertyChanged("EtniaPaciente");

                if (base.Entity.EntityState == EntityState.Unchanged)
                {
                    _context.ObjectStateManager.ChangeObjectState(base.Entity, EntityState.Modified);
                }
            }
        }

        public BitmapImage Foto
        {
            get
            {

                BitmapImage image = null;

                if (base.Entity.Foto != null)
                {
                    image = new BitmapImage();
                    image.BeginInit();
                    MemoryStream ms = new MemoryStream(base.Entity.Foto);
                    image.StreamSource = ms;
                    image.EndInit();
                }

                return image;
            }
        } 
        #endregion

        #region Contato

        public IEnumerable<Endereco> EnderecoCollection
        {
            get { return base.Entity.Enderecos; }
        }

        private Endereco _selectedEndereco;

        public Endereco SelectedEndereco
        {
            get { return _selectedEndereco; }
            set
            {
                _selectedEndereco = value;

                //_selectedEndereco.PropertyChanged += (s, e) => base.OnPropertyChanged(e);
                
                base.OnPropertyChanged("SelectedEndereco");
            }
        }

        private Estado _selectedEstado;

        public Estado SelectedEstado
        {
            get { return _selectedEstado; }
            set
            {
                if (_selectedEstado != value)
                {
                    _selectedEstado = value;
                    base.OnPropertyChanged("SelectedEstado");
                }
            }
        }





        

        #endregion


        #endregion

        #region Lookup properties

        public IEnumerable<EstadoCivil> EstadoCivilCollection
        {
            get
            {
                return _context.EstadoCivilSet.ToList();
            }
        }

        public IEnumerable<GrupoEspecifico> GrupoEspecificoCollection
        {
            get
            {
                return _context.GrupoEspecificoSet.ToList();
            }
        }

        public IEnumerable<Etnia> EtniaCollection
        {
            get
            {
                return _context.EtniaSet.ToList();
            }
        }

        public IEnumerable<TipoEndereco> TipoEnderecoCollection
        {
            get
            {
                return _context.TipoEnderecoSet.ToList();
            }
        }

        public IEnumerable<Estado> EstadoCollection
        {
            get
            {
                return _context.EstadoSet.ToList();
            }
        }

        public IEnumerable<Cidade> CidadeCollection
        {
            get
            {
                if (SelectedEstado != null)
                {
                    return _context.CidadeSet.Where(c => c.Estado.IdEstado == SelectedEstado.IdEstado).ToList();
                }
                else
                {
                    return _context.CidadeSet.ToList();
                }                
            }
        }

        #endregion


        #region Commands

        public ICommand OkCommand { get; private set; }
        public ICommand CancelarCommand { get; private set; }
        public ICommand AddEnderecoCommand { get; private set; }
        public ICommand RemoveEnderecoCommand { get; private set; }
        public ICommand OpenFotoFileCommand { get; private set; }

        private void SavePaciente()
        {
            _context.SaveChanges();
            //MessageBox.Show("Pessoa salva com sucesso", "Salvar", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private bool CanSavePaciente()
        {
            return base.Entity != null &&
                   base.Entity.EntityState != EntityState.Unchanged;
        }

        private void Cancelar()
        {
            
        }

        private void AddEndereco()
        {
            Endereco endereco = Endereco.CreateEndereco(0, string.Empty, "<Endereço>", 0, "<Complemento>", "<Bairro>");
            base.Entity.Enderecos.Add(endereco);
            this.SelectedEndereco = endereco;
            _context.ObjectStateManager.ChangeObjectState(base.Entity, EntityState.Modified);
        }

        private void RemoveEndereco()
        {
            base.Entity.Enderecos.Remove(SelectedEndereco);
            _context.ObjectStateManager.ChangeObjectState(base.Entity, EntityState.Modified);
        }

        private bool CanRemoveEndereco()
        {
            return SelectedEndereco != null;
        }

        private void OpenFotoFile()
        {
            OpenFileDialog dlgOpenFile = new OpenFileDialog();
            dlgOpenFile.DefaultExt = ".jpg";
            dlgOpenFile.Filter = "Imagens JPEG (*.jpg)|*.jpg";

            var result = dlgOpenFile.ShowDialog();
                       
            if (result == DialogResult.OK)
            {
                Entity.Foto = File.ReadAllBytes(dlgOpenFile.FileName);
                base.OnPropertyChanged("Foto");
            }

        } 

        #endregion


    }
}
